# Copyright 2004 Daniel Henninger <jadestorm@nc.rr.com>
# Licensed for distribution under the GPL version 2, check COPYING for details

from twisted.internet import task
from tlib import oscar
from tlib.domish import Element
import groupchat
import aimt
import config
import debug
import utils

# The name of the transport
name = "AIM Transport"

# The transport's version
version = "0.4a"

# This should be set to the identity of the gateway
id = "aim"

# This should be set to the identity of the conference gateway, blank if none
confid = ""

# Set to True if spool directory entries need to be mangled @ -> %
mangle = True

# This should be set to the name space roster entries are in in the spool
namespace = "aimtrans:data"

# This function should return an xml element as it should exist in the spool
def formRegEntry(username, password):
	reginfo = Element((None, "aimtrans"))

	logoninfo = reginfo.addElement("logon")
	logoninfo.attributes["id"] = username
	logoninfo.attributes["pass"] = password

	return reginfo

# This function should, given a spool xml entry, pull the username and password
# out of it and return them
def getAttributes(base):
	username = ""
	password = ""

	for child in base.elements():
		try:
			if(child.name == "logon"):
				username = child.getAttribute("id")
				password = child.getAttribute("pass")
		except AttributeError:
			continue

	return username, password

# This function should return true if the JID is a group JID, false otherwise
def isGroupJID(jid):
	if (jid[0] == "#"):
		return True
	else:
		return False

# This function translates an AIM screen name to a JID
def aim2jid(aimid):
	retstr = aimid.replace(' ', '')
	return retstr.replace('@', '%') + "@" + config.jid

# This function translates a JID to an AIM screen name
def jid2aim(jid):
	return unicode(jid[:jid.find('@')].replace('%', '@'))

# This function is called to handle legacy id translation to a JID
translateAccount = aim2jid

# This class handles groupchats with the legacy protocol
class LegacyGroupchat(groupchat.BaseGroupchat):
	def __init__(self, session, resource, ID=None, existing=False, switchboardSession=None):
		groupchat.BaseGroupchat.__init__(self, session, resource, ID)
		debug.log("LegacyGroupchat: \"%s\" created" % (self.roomJID()))
		pass
	
	def removeMe(self):
		pass

	def sendLegacyMessage(self, message):
		pass
	
	def sendContactInvite(self, contactJID):
		pass

# This class handles most interaction with the legacy protocol
class LegacyConnection(aimt.AIMConnection):
	""" A glue class that connects to the legacy network """
	def __init__(self, username, password, session):
		debug.log("LegacyConnection: __init__")
		self.session = session
		self.savedShow = None
		self.savedFriendly = None
		aimt.AIMConnection.__init__(self, username, password)
	
	def removeMe(self):
		debug.log("LegacyConnection: removeMe")
		aimt.AIMConnection.removeMe(self)
		utils.mutilateMe(self)
	
	def sendMessage(self, dest, body):
		debug.log("LegacyConnection: sendMessage %s %s" % (dest, body))
		aimt.AIMConnection.sendMessage(self, dest, body)

	def newResourceOnline(self, resource):
		debug.log("LegacyConnection: newResourceOnline %s" % (resource))
		aimt.AIMConnection.resendBuddies(self, resource)
	
 	def setStatus(self, show, friendly):
		debug.log("LegacyConnection: setStatus %s %s" % (show, friendly))

		self.savedShow = show
		self.savedFriendly = friendly

		if (not self.session.ready):
			return

		if (show in ["online", None]):
			aimt.AIMConnection.setAway(self)
			self.session.sendPresence(to=self.session.jabberID, fro=config.jid, show=None)
		else:
			aimt.AIMConnection.setAway(self, friendly)
			self.session.sendPresence(to=self.session.jabberID, fro=config.jid, show=show, status=friendly)

        def buildFriendly(self, status):
		friendly = self.jabberID[:self.jabberID.find('@')]
		if(status and len(status) > 0):
			friendly += " - "
			friendly += status
		if(len(friendly) > 127):
			friendly = friendly[:124] + "..."
		debug.log("Session: buildFriendly(%s) returning \"%s\"" % (self.jabberID, friendly))
		return friendly
	
	def jabberSubscriptionReceived(self, source, subtype):
		debug.log("LegacyConnection: jabberSubscriptionReceived %s %s" % (source, subtype))
		aimt.AIMConnection.jabberSubscriptionReceived(self, source, subtype)

	def userTypingNotification(self, dest, composing):
		debug.log("LegacyConnection: userTypingNotification %s %s" % (dest,composing))
		if (composing):
			aimt.AIMConnection.sendTypingNotify(self, "begin", dest)
		else:
			aimt.AIMConnection.sendTypingNotify(self, "finish", dest)

	def jabberVCardRequest(self, vcard, user):
		debug.log("LegacyConnection: jabberVCardRequest %s" % (user))
		return aimt.AIMConnection.getvCard(self, vcard, user)
